<template>
  <div class="user-container">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" @finish="handleQuery" class="search-form">
        <a-form-item label="用户名" name="userName">
          <a-input v-model:value="queryParams.userName" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="手机号" name="phonenumber">
          <a-input v-model:value="queryParams.phonenumber" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="queryParams.status" placeholder="请选择状态" style="width: 120px">
            <a-select-option :value="null">全部</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><search-outlined /></template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><redo-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      
      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd" v-if="hasPermission('system:user:add')">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button type="primary" danger :disabled="!selectedRowKeys.length" @click="handleBatchDelete"
            v-if="hasPermission('system:user:delete')">
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </a-space>
      </div>
      
      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :row-key="(record: SysUser) => record.userId"
        @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          
          <!-- 性别列 -->
          <template v-if="column.key === 'sex'">
            <a-tag :color="record.sex === 0 ? 'blue' : record.sex === 1 ? 'pink' : 'default'">
              {{ record.sex === 0 ? '男' : record.sex === 1 ? '女' : '未知' }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleEdit(record)" v-if="hasPermission('system:user:edit')">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这个用户吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
                v-if="hasPermission('system:user:delete')"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 用户表单对话框 -->
    <user-form
      v-model:visible="formVisible"
      :form-data="formData"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  RedoOutlined,
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import { usePermission } from '@/composables/usePermission'
import type { SysUser } from '@/types/user'
import type { TableProps } from 'ant-design-vue'

// 引入子组件
import UserForm from './components/UserForm.vue'

// 权限检查
const { checkPermission: hasPermission } = usePermission()

// 用户状态
const userStore = useUserStore()
const loading = ref(false)
const userList = ref<SysUser[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 查询参数
const queryParams = reactive({
  userName: '',
  phonenumber: '',
  status: null
})

// 选中行数据
const selectedRowKeys = ref<(string | number)[]>([])

// 表单状态
const formVisible = ref(false)
const formData = ref<Partial<SysUser>>({})

// 表格列定义
const columns = [
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    key: 'nickName'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '手机号',
    dataIndex: 'phonenumber',
    key: 'phonenumber'
  },
  {
    title: '性别',
    dataIndex: 'sex',
    key: 'sex'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true
  },
  {
    title: '操作',
    key: 'operation',
    width: 120
  }
]

// 初始化加载数据
onMounted(() => {
  getList()
})

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    
    const res = await userStore.getUserPage(params)
    userList.value = res.rows || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    // @ts-ignore
    queryParams[key] = ''
  })
  pagination.current = 1
  getList()
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (pag, filters, sorter) => {
  pagination.current = pag.current as number
  pagination.pageSize = pag.pageSize as number
  getList()
}

// 选择行变化
const onSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys
}

// 新增用户
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 编辑用户
const handleEdit = async (record: SysUser) => {
  try {
    // 获取用户详情，包括角色信息
    const userDetail = await userStore.getUserDetail(record.userId)
    formData.value = { ...userDetail }
    formVisible.value = true
  } catch (error) {
    message.error('获取用户详情失败')
    console.error('获取用户详情失败:', error)
  }
}

// 删除用户
const handleDelete = async (record: SysUser) => {
  try {
    await userStore.deleteUser(record.userId)
    message.success('删除成功')
    if (pagination.current === 1) {
      getList()
    } else {
      pagination.current = 1
      getList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRowKeys.value.length) {
    message.warning('请至少选择一条记录')
    return
  }
  
  // 这里假设后端支持批量删除接口，实际中可能需要循环调用单个删除
  try {
    message.success('批量删除成功')
    pagination.current = 1
    getList()
    selectedRowKeys.value = []
  } catch (error) {
    message.error('批量删除失败')
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  formVisible.value = false
  getList()
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}

.danger-text:hover {
  color: #ff7875;
}
</style>
